package com.tanhua.appserver.service;


import cn.hutool.crypto.digest.MD5;
import com.tanhua.api.UserApi;
import com.tanhua.autoconfig.template.SMTemplate;
import com.tanhua.model.pojo.User;
import com.tanhua.utils.JwtUilt;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.multipart.MultipartFile;


import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class UserService {


    @Autowired
    private SMTemplate smTemplate;

    @Autowired
    private RedisTemplate redisTemplate;

    @DubboReference
    private UserApi userApi;


    private String CHECK_CODE = "CHECK_CODE_";


    public void send(Map map){

        //从集合中拿到手机号
        String phone = (String) map.get("phone");

        //生成随机四位验证码
        //String code = RandomStringUtils.randomNumeric(4);

        String code = "123456";
        //使用第三方接口发送短信
        //smTemplate.sendSms(phone,code);

        //将其存入redis中,并设置过期时间为5分钟
        redisTemplate.opsForValue().set(CHECK_CODE+phone, code, 5, TimeUnit.MINUTES);

    }


    public Map loginVerification(Map map){

        //从集合中拿道数据
        String phone = (String) map.get("phone");
        String phoneKey = CHECK_CODE + phone;
        String verificationCode = (String) map.get("verificationCode");

        //从redis中拿到验证
        String code = (String) redisTemplate.opsForValue().get(phoneKey);

        System.out.println(code);
        System.out.println(verificationCode);

        //对比数据 失败抛出异常
        if (!verificationCode.equals(code)){
            throw new RuntimeException("验证码有误");
        }

        //对比成功后,将redis中的验证码删除
        redisTemplate.delete(phoneKey);

        HashMap<String, Object> result = new HashMap<>();
        boolean isNew = false;

        //将用户id和手机号存入
        HashMap<String, String> userMap = new HashMap<>();


        //判断是否为新用户
        User user = userApi.byMobileUser(phone);

        if (user == null){
            user = new User();

            //不存在时就组装并保存该用户信息
            user.setMobile(phone);
            user.setPassword(MD5.create().digestHex("123456"));
            isNew  = true;
            Long userId = userApi.saveUser(user);
            user.setId(userId);

            System.out.println(userId);
        }

        userMap.put("id", String.valueOf(user.getId()));
        userMap.put("phone", phone);

        //将该用户信息做成token返回到前端
        String token = JwtUilt.createToken(userMap);

        //组装数据返回前端
        result.put("token",token);
        result.put("isNew",isNew);

        return result;
    }


}
